package ua.pp.bizon.yandex.uploader;

import ua.pp.bizon.yandex.api.QueryMBean;
import ua.pp.bizon.yandex.api.impl.Element;
import ua.pp.bizon.yandex.jmx.Service;

import java.util.List;

import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class QueryClient implements QueryMBean {

	private final Log log = LogFactory.getLog(getClass());

	private final MBeanServerConnection server;
	private final ObjectName objectName;

	public QueryClient(MBeanServerConnection connection) throws MalformedObjectNameException {
		this.server = connection;
		objectName = new ObjectName(Service.OBJECT_NAME);
	}

	// @Override
	// public Element getLastActivity() {
	// try {
	// return (Element) server.getAttribute(objectName, "LastActivity");
	// } catch (Exception e) {
	// log.error(e.getMessage(), e);
	// }
	// return null;
	// }

	@Override
	public void addActivity(Element element) {
		try {
			server.invoke(objectName, "addActivity", new Object[] { element }, new String[] { Element.class.getName() });
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Element> getActivities() {
		try {
			return (List<Element>) (server.getAttribute(objectName, "Activities"));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	// @Override
	// public void finished() {
	// try {
	// server.invoke(objectName, "finished", new Object[] {}, new String[] {});
	// } catch (Exception e) {
	// log.error(e.getMessage(), e);
	// }
	// }

	@Override
	public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) {
		try {
			server.addNotificationListener(objectName, listener, filter, handback);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

}
